package com.keyue.common.excel4j;

import com.keyue.common.constant.Constant;
import com.keyue.common.constant.ServerResultCode;
import com.keyue.common.exception.BusinessException;
import com.keyue.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.groups.Default;
import java.util.Set;

/**
 * @author fanzhenyu
 * @date 2023-02-23
 */
@Slf4j
public class ExcelValidator {


    private static Validator validator = Validation.buildDefaultValidatorFactory().getValidator();

    /**
     * 校验遇到第一个不合法的字段直接返回不合法字段，后续字段不再校验
     * @param <T>
     * @return
     */
    public static <T> void validateEntity(T obj) {
        Set<ConstraintViolation<T>> set = validator.validate(obj, Default.class);
        String err = collectError(set);
        if (StringUtils.isNotBlank(err)){
            throw new BusinessException(ServerResultCode.ILLEGAL_ARGUMENT.getErrorCode(),err);
        }
    }

    private static <T> String collectError(Set<ConstraintViolation<T>> set) {
        StringBuilder result = new StringBuilder();
        if (set != null && !set.isEmpty()) {
            for (ConstraintViolation<T> cv : set) {
                result.append(cv.getMessage());
                result.append(Constant.SEMICOLON_CHARACTER);
            }
        }
        return result.toString();
    }



}
